from django.shortcuts import render
from django.views import View
from .models import TestModels
from django.http import JsonResponse, HttpResponse
import csv
import chardet
# Create your views her


class Test1View(View):
    def get(self, request):
        test_queryset_count = TestModels.objects.all().count()
        return JsonResponse({"test_queryset_count": test_queryset_count})

    def post(self, request):
        test_list = []
        for i in range(10):
            test_list.append(
                TestModels(username="陈海峰" + str(i), password="123" + str(i), age=1 + i)
            )
        create_count = TestModels.objects.bulk_create(test_list)
        return JsonResponse({"create_count": len(create_count)})

from io import BytesIO
import codecs
class CsvView(View):
    def get(self, request):
        output = BytesIO()

        # 使用 GBK 编码打开字节流对象并创建 CSV 写入器
        writer = csv.writer(codecs.getwriter("gbk")(output))

        # 获取数据并写入 CSV 文件
        t = list(TestModels.objects.all().values_list())
        writer.writerows(t)

        # 创建响应对象，并将字节流对象的内容作为响应体
        response = HttpResponse(content_type="text/csv")
        response["Content-Disposition"] = 'attachment; filename="somefilename.csv"'
        output.seek(0)
        response.write(output.getvalue())

        return response
    
    def post(self, request):
        file = request.FILES["file"]
        content = file.read()
        data = csv.reader(content.decode("gbk").splitlines())
        for row in data:
            TestModels.objects.filter(id=row[0]).update(username=row[1])
            print(row)
        return JsonResponse({"file": file.name})